// 实现这个项目的构建任务
const { series, parallel, src, dest,watch } = require("gulp")
const loadPlugins = require("gulp-load-plugins")
const plugins = loadPlugins()
const sass = require("gulp-sass")(require('sass'));
const fs = require("fs")
const del = require("del")
const browserSync = require("browser-sync")
const bs = browserSync.create()
//series串行执行任务，parallel是并行执行任务
const style = () => {
    return src("src/assets/styles/*.scss", { base: "src" })
        .pipe(sass({outputStyle:"expanded"}))
        .pipe(dest("dist"))
        .pipe(bs.reload({stream: true}))
}


const script = () => {
    return src("src/assets/scripts/*.js",{base: "src"})
    .pipe(plugins.babel({presets:["@babel/preset-env"]}))
    .pipe(dest("dist"))
}



//html文件处理



const  pageindex = ()=>{
    return src("src/*.html")
    .pipe(plugins.swig())
    .pipe(dest("dist"))
}
const pagefloder=()=>{
    return src("src/*/*.html")
    .pipe(plugins.swig())
    .pipe(dest("dist"))
}
const page = parallel(pageindex, pagefloder)


//图片文件打包

const  image = ()=>{
    return src("src/assets/images/**",{ base:"src"})
    .pipe(plugins.imagemin())
    .pipe(dest("dist"))
}

const font = () => {
    return src("src/assets/fonts/**", { base: "src" })
      .pipe(plugins.imagemin())
      .pipe(dest("dist"))
  }



const extra =()=>{
    return src("public.**",{ base:"public"})
    .pipe(dest("dist"))
}
///清除任务
const clean = ()=>{
    return del(["dist"])
}
const useref = () => {
    return src('dist/*.html', {base: 'dist'})
      .pipe(plugins.useref({searchPath: ['dist', '.']}))
      .pipe(plugins.if(/\.js$/, plugins.uglify()))
      .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
      .pipe(plugins.if(/\.html$/, plugins.htmlmin({
        collapseWhitespace: true,
        removeComments: true,
        minifyCss: true, // 压缩页面css
        minifyJs: true // 压缩页面js
      })))
      .pipe(dest('release')) // 使用release 从 dist文件读取编写到release
  }


//serve
const serve = ()=>{
    watch("src/assets/styles/*.scss", style)
    watch("src/assets/styles/*.scss", script)
    watch("src/**/*.html", html)
    watch([
      "src/assets/images/**", 'src/assets/fonts/**', "public/**"
    ], bs.reload)



    bs.init({
        notify:false,
        port:2080,
        open:false,
        // files:"dist/**",
        server:{    
            baseDir:["dist", "src", "public"],
            routes: {
                "/node_modules":"node_modules"
            }
        }
    })
}





const compile =parallel(style,script,page,image,font,extra)
const build = series(clean,compile)
const start = series(parallel(compile), serve)
module.exports = {
    build,
    serve,
    start,
    useref,
    clean,
    // image
}
// "clean": "gulp clean",
// "lint": "gulp lint",
// "serve": "gulp serve",
// "build": "gulp build",
// "start": "gulp start",
// "deploy": "gulp deploy --production"